/**
 * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.commodity.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.springblade.common.constant.RoleIdConstant;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.RedisUtil;
import org.springblade.modules.commodity.entity.Commodity;
import org.springblade.modules.commodity.entity.CommodityParams;
import org.springblade.modules.commodity.entity.CommodityType;
import org.springblade.modules.commodity.mapper.CommodityMapper;
import org.springblade.modules.commodity.mapper.CommodityParamsMapper;
import org.springblade.modules.commodity.service.ICommodityService;
import org.springblade.modules.commodity.vo.CommodityVO;
import org.springblade.modules.system.entity.Dict;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.mapper.UserMapper;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 商品表 服务实现类
 *
 * @author Blade
 * @since 2021-01-18
 */
@Service
@AllArgsConstructor
public class CommodityServiceImpl extends BaseServiceImpl<CommodityMapper, Commodity> implements ICommodityService {

	private RedisUtil redisUtil;
	private UserMapper userMapper;
	private CommodityParamsMapper commodityParamsMapper;

	@Override
	public IPage<CommodityVO> selectCommodityPage(IPage<CommodityVO> page, CommodityVO commodity) {
		List<CommodityVO> voList = baseMapper.selectCommodityPage(page, commodity);
		List<CommodityVO> commodityVOList = new ArrayList<>();
		for (CommodityVO commodityVO : voList) {
			String[] split = commodityVO.getSpecs().split("/");
			String[] price = commodityVO.getCommodityPrice().split("/");
			List<Double> priceList = toDouble(price);
			List<Map<String,Object>> list = new ArrayList<>();
			int i =0;
			for (String s : split) {
				Map<String,Object> map = new HashMap<>();
				map.put("label",i);
				map.put("value",s);
				i++;
				list.add(map);
			}
			List<Double> collect = priceList.stream().sorted().collect(Collectors.toList());
			List<String> lists = new ArrayList<>(Arrays.asList(price));
			commodityVO.setSpecsList(list);
			commodityVO.setPriceList(lists);
			commodityVO.setPriceRange(collect.get(0)+"~"+collect.get(collect.size()-1));
			commodityVOList.add(commodityVO);
		}
		return page.setRecords(commodityVOList);
	}

	public List<Double> toDouble(String[] strings){
		List<Double> list = new ArrayList<>();
		for (String s : strings) {
			list.add(Func.toDouble(s));
		}
		return list;
	}


	@Override
	public Boolean history(Commodity commodity) {
		if (Func.isEmpty(redisUtil.get("history:" + SecureUtil.getUserId()))) {
			List<Commodity> list = new ArrayList<>();
			list.add(commodity);
			redisUtil.set("history:" + SecureUtil.getUserId(), list, 30, TimeUnit.DAYS);
		} else {
			List<Commodity> myHistory = (List<Commodity>)redisUtil.get("history:" + SecureUtil.getUserId());
			myHistory.add(commodity);
			myHistory = myHistory.stream().distinct().collect(Collectors.toList());
			redisUtil.set("history:" + SecureUtil.getUserId(), myHistory, 30, TimeUnit.DAYS);
			}
		return true;
	}

	@Override
	public List<Commodity> selectHistory() {
		List<Commodity> history = (List<Commodity>)redisUtil.get("history:" + SecureUtil.getUserId());
		history = history.stream().distinct().collect(Collectors.toList());
		return history;
	}

	@Override
	public IPage<CommodityVO> selectPage(IPage<CommodityVO> page, CommodityVO commodity) {
		if(Func.isNotEmpty(SecureUtil.getUser())){
		if (SecureUtil.getUser().getRoleName().equals(RoleIdConstant.STORE_NAME)){
			commodity.setCreateUser(SecureUtil.getUserId());
			return page.setRecords(baseMapper.selectPage(page, commodity));
		}
		}
		if (Func.isNotEmpty(commodity.getCreateUser())){
			return page.setRecords(baseMapper.selectPage(page, commodity));
		}
		return page.setRecords(baseMapper.selectCommodityPage(page, commodity));
	}

	@Override
	public Boolean submits(Commodity commodity) {
		String[] price = commodity.getCommodityPrice().split("/");
		String[] specs = commodity.getSpecs().split("/");
		if (price.length!=specs.length){
			throw new ServiceException("商品价格数量和商品规格数量不一致!");
		}
		BladeUser user = SecureUtil.getUser();
		if (Func.isNotEmpty(user)){
			User users = userMapper.selectById(SecureUtil.getUserId());
			commodity.setStoreName(users.getName());
		}
		return saveOrUpdate(commodity);
	}

	@Override
	public List<Dict> selectType() {
		List<CommodityType> commodityTypes = baseMapper.selectType();
		List<Dict> dictList = new ArrayList<>();
		for (CommodityType type : commodityTypes) {
			Dict dict = new Dict();
			dict.setDictKey(Func.toInt(type.getId()));
			dict.setDictValue(type.getCommodityType());
			dictList.add(dict);
		}
		return dictList;
	}

	@Override
	public CommodityType selectTypeName(String type) {
		return baseMapper.selectTypeName(type);
	}

	@Override
	public CommodityVO selectId(Long id) {
		Commodity commodity = baseMapper.selectById(id);
		String[] split = commodity.getSpecs().split("/");
		String[] price = commodity.getCommodityPrice().split("/");
		List<String> lists = new ArrayList<>(Arrays.asList(price));
		CommodityVO commodityVO = BeanUtil.copy(commodity, CommodityVO.class);
		List<Map<String,Object>> list = new ArrayList<>();
		int i =0;
		for (String s : split) {
			Map<String,Object> map = new HashMap<>();
			map.put("label",i);
			map.put("value",s);
			i++;
			list.add(map);
		}
		List<Double> priceList = toDouble(price);
		List<Double> collect = priceList.stream().sorted().collect(Collectors.toList());
		commodityVO.setPriceRange(collect.get(0)+"~"+collect.get(collect.size()-1));
		commodityVO.setSpecsList(list);
		commodityVO.setPriceList(lists);
		return commodityVO;
	}
}
